const express = require('express')
const cors = require('cors')
const userRouter = require('./router/user')
const userinfoRouter = require('./router/userinfo')
const artcateRouter = require('./router/artcate')
const articleRouter = require('./router/article')
const Joi = require('joi')
const app = express()
app.use(express.urlencoded({ extended: false }))//解析x-www格式
app.use(cors())
app.use((req, res, next) => {
    res.cc = (err, status = 1) => {
        res.send({
            status,
            message: err instanceof Error ? err.message : err
        })
    }
    next()
})
const expressJWT = require('express-jwt')
const config = require('./config')
app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/api/] }))

app.use('/api', userRouter)
app.use('/my', userinfoRouter)
app.use('/my/article', artcateRouter)
app.use('/my/article', articleRouter)

app.use((err, req, res, next) => {
    if (err instanceof Joi.ValidationError) return res.cc(err)
    if (err.name === 'UnauthorizedError') return res.cc('身份认证失败')
    res.cc('未知错误')
})
app.listen(3007, () => {
    console.log('api_server runing at http://127.0.0.1:3007');
})